package com.jxd.ordering.controller;

import com.jxd.ordering.annotation.CheckPermission;
import com.jxd.ordering.exception.CommonEnum;
import com.jxd.ordering.exception.serviceexception.PermissionNotAllowedException;
import com.jxd.ordering.model.Admin;
import com.jxd.ordering.model.ResultBody;
import com.jxd.ordering.service.IAdminService;
import com.jxd.ordering.service.IUserService;
import com.jxd.ordering.util.PermissionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @ClassName AdminController
 * @Description TODO
 * @Author Ankailong
 * @Date 2022/9/28
 * @Version 1.0
 */
@RestController
public class AdminController {
    @Autowired
    public IAdminService adminService;
    @Autowired
    private IUserService userService;

    /**
     * 新增管理员信息
     * level: 4
     * @param admin 管理员实体类
     * @return 是否新增成功
     */
    @CheckPermission("4")
    @RequestMapping("/addAdmin")
    public ResultBody addAdmin(@RequestBody Admin admin) {
        return adminService.addAdmin(admin) ? ResultBody.success() : ResultBody.error(CommonEnum.INTERNAL_SERVER_ERROR);
    }

    /**
     * 修改管理员信息
     * level: 4
     * @param admin 管理员实体类
     * @return 是否修改成功
     */
    @RequestMapping("editAdmin")
    public ResultBody editAdmin(@RequestBody Admin admin, HttpServletRequest request) throws PermissionNotAllowedException {
        //临时授权
        if (admin.getAdminno() != userService.getUsernoByUserid(Integer.parseInt(request.getAttribute("userid").toString()))) {
            PermissionUtil.PermissionControl(request.getAttribute("permission"), 4);
        }
        return adminService.editAdmin(admin) ? ResultBody.success() : ResultBody.error(CommonEnum.INTERNAL_SERVER_ERROR);
    }

    /**
     * 批量删除管理员信息
     * level: 4
     * @param adminnos 管理员编号列表
     * @return 是否删除成功
     */
    @CheckPermission("4")
    @RequestMapping("delAdmin")
    public ResultBody delAdmin(@RequestBody List<Integer> adminnos) {
        return adminService.delAdmin(adminnos.stream().mapToInt(Integer::intValue).toArray()) ? ResultBody.success() : ResultBody.error(CommonEnum.INTERNAL_SERVER_ERROR);
    }

    /**
     * 按管理员编号查询管理员信息
     * level: 4
     * @param adminno 管理员编号
     * @return 查询结果
     */
    @RequestMapping("getAdminByAdminno")
    public Admin getAdminByAdminno(int adminno, HttpServletRequest request) throws PermissionNotAllowedException {
        //临时授权
        if (adminno != userService.getUsernoByUserid(Integer.parseInt(request.getAttribute("userid").toString()))) {
            PermissionUtil.PermissionControl(request.getAttribute("permission"), 4);
        }
        return adminService.getAdminByAdminno(adminno);
    }
}
